//
//  InAppPurchase.m
//  iStock Global
//
//  Created by Andy on 2011/3/5.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "InAppPurchase.h"
#import "TSO_Setup_TableViewCell.h"
#import "InAppTableCell.h"
#import "AppDelegate.h"
#import "JSON.h"

@implementation InAppPurchase
@synthesize delegate,AppleDeglate  ;
@synthesize delegate_UIPopoverController;
@synthesize acv;
-(id) init{
	self= [ super init];
    if (self ) {
		 
		
	}
	return self;
	
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation {
    return YES;
}


//自設初始化
-(void)get_navcontroller:(navcontroller *)nd{
	navdelegete=nd;
}
-(void)initTitle:(NSString *)bartitle{
	self.title=bartitle;
	is_init_from_maindelegete=YES;	
	NSLog(@"initTitle");
	
}
-(void)initImage:(UIImage*)image{
	self.tabBarItem.image= image ;
	NSLog(@"initImage");
}
-(id)initAddStockWatchlist{
    self= [super init] ;
    
	if (self ) {
		NSLog(@"initAddStockWatchlist");
		is_init_from_addstockwatchlist=YES;		
	}
	return self;
}



// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
		NSLog(@"initWithNibName");
		is_init_from_addstockwatchlist=NO;
		is_init_from_maindelegete=NO;	 		
		
    }
    return self;
} 
-(void)viewWillAppear:(BOOL)animated{
    //每次畫面出現都會顯示一次
	NSLog(@"viewWillAppear");
	
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        if (ActivityIndicator!=nil){
          ActivityIndicator.frame=CGRectMake(myTable.frame.size.width/2-20,myTable.frame.size.height/2-20, 40, 40) ; 
        }
        
    }
	else{
        
        
        if ([IAP.Product_title count]==0) {
            [IAP requestProUpgradeProductData];	
            
            ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(110,150, 100, 100)];	
            ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleWhiteLarge;
            ActivityIndicator.layer.backgroundColor=[[UIColor grayColor] CGColor];
            ActivityIndicator.alpha=0.5;
            ActivityIndicator.layer.cornerRadius=6.0;
            
            [self.view addSubview:ActivityIndicator];			
            
             ActivityIndicator.frame=CGRectMake(myTable.frame.size.width/2-20,myTable.frame.size.height/2-20, 40, 40) ;               
            [ActivityIndicator startAnimating];		
        }  
    }
	
		
	

}
- (void)loadView {
	
    
    //購物物件產生
    IAP=[[InAppPurchaseManager alloc] init];	
	IAP.delgete=self;
	 
    //很重要 如果沒有這一段 則 app stor 不會回應 delegete
	//[[SKPaymentQueue defaultQueue] addTransactionObserver:IAP];	
	
    if (is_init_from_maindelegete==YES) {
		NSLog(@"is_init_from_maindelegete");
			
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
		
		
            if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ){
                //垂直
                UIView *mainview;
                mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
                self.view=mainview;
                [mainview release];
                
                self.view.backgroundColor=[UIColor lightTextColor];           
                myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 664.0f)  style:UITableViewStyleGrouped];        
                
       }
            else{
                //水平
                UIView *mainview;
                mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
                self.view=mainview;
                [mainview release];
                
                self.view.backgroundColor=[UIColor lightTextColor];           
                myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 664.0f)  style:UITableViewStyleGrouped];        
                

                
                                
            }
            
            
            
                    
            
		}
        else{
            UIView *mainview;
            mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
            self.view=mainview;
            [mainview release];
            self.view.backgroundColor=[UIColor lightTextColor];          
            myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, self.view.frame.size.height)  style:UITableViewStyleGrouped];
        
        }
        
       // myTable.dataSource = self;	//連結資料 UITableViewDataSource
		//myTable.delegate=self; //連結動作 UITableViewDelegate	
		[self.view addSubview:myTable];		
		NSLog(@"is_init_from_maindelegete_end");
		
	} 
	
	if (is_init_from_addstockwatchlist==YES) {
		NSLog(@"is_init_from_addstockwatchlist");        
        UINavigationBar *nav;
        
        UIView *mainview;        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
            
            
            if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ){
                //垂直
                mainview=[[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 600.0f, 600.0f)];
                self.view=mainview;
                [mainview release];
                
                self.view.backgroundColor=[UIColor lightTextColor];	
                
                nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 540.0f, 48.0f)];	
                	myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f, 540.0f, 580.0f)  style:UITableViewStyleGrouped];                
                
            }
            else{
                //水平
                /*
                mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
                self.view=mainview;
                self.view.backgroundColor=[UIColor lightTextColor];	
                
                nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];	
                	myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f, 320.0f, 412.0f)  style:UITableViewStyleGrouped]; 
                 */
                mainview=[[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 600.0f, 600.0f)];
                self.view=mainview;
                [mainview release];
                
                self.view.backgroundColor=[UIColor lightTextColor];	
                
                nav =  [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 540.0f, 48.0f)]  ;
                myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f, 540.0f, 580.0f)  style:UITableViewStyleGrouped];                
                
            }
            
            
            
            
            
        }
        else{
           
            mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
            self.view=mainview;
            [mainview release];
            
            self.view.backgroundColor=[UIColor lightTextColor];	
                       
            nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];	
            
        	myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f, 320.0f, self.view.frame.size.height)  style:UITableViewStyleGrouped];
            
            
        }
        
        
        
        
       		UIBarButtonItem *barButton ;
		barButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done",@"完成")  style:UIBarButtonItemStylePlain target:self action:@selector(slideOut)];
		UINavigationItem *item;
		item = [[UINavigationItem alloc] initWithTitle:NSLocalizedString(@"Upgrade",@"升級")  ];
		[item setRightBarButtonItem: barButton];
       
		[nav pushNavigationItem:item animated:NO];
        
        
        [item release];		
		//UIBarButtonItem *rightButton =[[UIBarButtonItem alloc] initWithTitle:@"GoBack" style:UIBarButtonItemStyleDone target:self action:@selector(slideOut)];
		
	
		
		
		//myTable.dataSource = self;	//連結資料 UITableViewDataSource
		//myTable.delegate=self; //連結動作 UITableViewDelegate	
		[self.view addSubview:myTable];
		
		//[self.view addSubview:headerbutton];
		[mainview addSubview:nav ];
		[nav release];        
	}
	 
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
            
        if ([IAP.Product_title count]==0) {
            [IAP requestProUpgradeProductData];	
            
            ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(myTable.frame.size.width/2-20,myTable.frame.size.height/2-20, 40, 40)];
            
            
          
            ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            
            [self.view addSubview:ActivityIndicator];			
            
            [ActivityIndicator startAnimating];		
        }  
    }
    
    
     
     //標記:進度指示器 實體化(InAppPurchase.m)
     acv=[[ActivityIndicator_view alloc] init];
     acv.hidden=YES;
     acv.label_state.text=NSLocalizedString(@"Loading...","載入中.....");   
     [self.view addSubview:acv];
     //[acv release];    
     
        
	
}





/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 2;    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	if (section==0) {
         return [IAP.Product_title count];
    }
    else if(section==1){
         return 1;
    }
   	else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	    
    if (indexPath.section==0) {
        static NSString *CellIdentifier = @"TableCellAddStockWatchList";
        
        InAppTableCell *cell =(InAppTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[[InAppTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        }
        
        cell.cell1.text = NSLocalizedString([IAP.Product_title objectAtIndex:indexPath.row],"");	
        cell.cell1.font=[UIFont boldSystemFontOfSize:15];
        cell.cell2.text =[@"" stringByAppendingFormat: @"$%@", [IAP.Product_price objectAtIndex:indexPath.row] ];	
        cell.cell2.font=[UIFont boldSystemFontOfSize:15];
        cell.cell2.textColor=[UIColor blueColor];        
        return cell;    
    }
	else if(indexPath.section==1){
        static NSString *CellIdentifier = @"Cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        
        
        
        cell.textLabel.text =NSLocalizedString( @"Restore","回復已購買功能");	
        cell.textLabel.font=[UIFont boldSystemFontOfSize:20];
        cell.textLabel.textAlignment=UITextAlignmentCenter;
        
        return cell; 
        
        
    } 
    else{
    
        static NSString *CellIdentifier = @"Cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        
        
        
        cell.textLabel.text = @"";	
        cell.textLabel.font=[UIFont boldSystemFontOfSize:15];
        return cell; 
        
        
        
    }
	
	
    
   
	
}



//Table 表格行選定
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        //設定指示器的長寬
        ActivityIndicator.frame=CGRectMake(myTable.frame.size.width/2-20,myTable.frame.size.height/2-20, 40, 40) ;    
        
	    [ActivityIndicator startAnimating];			 
        
		[IAP  purchaseProUpgrade: [IAP.Product_id objectAtIndex:indexPath.row]] ;        
        
    }
    else if(indexPath.section==1){
        
        if (indexPath.row==0) {
             NSLog(@"Restore");
            [IAP restore_purchase];
        }
        
       
    }
      
	 
	
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *title = nil;
	if (section==0) {
		
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		int maxsymblos;
		maxsymblos=[[prefs objectForKey:@"MaxSymbolsWatchlist" ] intValue ];		
		 
        
        if ([[prefs objectForKey:@"iap_type" ] isEqualToString:@"Auto-Renewable Subscriptions"]) {
            title=NSLocalizedString(@"Expire Date:","到期日:");
            
            title=[title stringByAppendingFormat:@" %@ \nExpire Status:%@",p_expire_Date,p_expire_status ]; 
                
        }
        else{
            title=NSLocalizedString(@"Maximum number of stocks in each watchlist:","每個投資組合中股票的最大數量");
            title=[title stringByAppendingFormat:@" %i ",maxsymblos];
        }
        
		 
        
        
        
        
        
    }
    else if(section==1){
        
		title=NSLocalizedString(@"If you have purchase, unlock the limit by tapping restore, and it will cost free.","如果你已經購買過此項升級服務,請按下回復已購買功能,它將是免費的.");
		        
        
    }
	
	return title;	
}

 


- (void)dealloc {	
	[IAP release];
	[myTable release];
	 
	
	[super dealloc];
}
#pragma mark -
#pragma mark  ActivityIndicator

-(void)start_ActivityIndicator_view:(NSString *)label_text progress_value:(float)prv{
    NSLog(@"start_ActivityIndicator_view=%f",prv);
    acv.hidden=NO;
    acv.label_state.text=label_text;
    acv.progbar.hidden=NO;
    acv.progbar.progress=prv;
} 
-(void)stop_ActivityIndicator_view{
    acv.hidden=YES;
}

#pragma mark -
#pragma mark  網路商店購買成功與失敗 交易結束
 
-(void)sucess_purchase{
	NSLog(@"網路商店購買成功");
	[myTable reloadData];
	[ActivityIndicator stopAnimating];	
}
-(void)productsRequest_failedTransaction{
    [ActivityIndicator stopAnimating];	
}
-(void)productsRequest_finishTransaction{
    [ActivityIndicator stopAnimating];
}
-(void)productsRequest_check_iap_expire_date{
    [self record_check_iap_expire];
}

#pragma mark -
#pragma mark 以網頁HTTP url方式 POST資料

//標記:以網頁HTTP url方式 POST資料

-(void)record_check_iap_expire{
    
    
    NSString *BundleIdentifier;
    BundleIdentifier=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];     
    
    //取出device 資料
	UIDevice *device = [UIDevice currentDevice];
	NSString *device_uniqueIdentifier = [device uniqueIdentifier];    
 
    //另外php 為record_login.php
    
    NSURL *url = [NSURL URLWithString:@"http://www.xxtradexx.com/php_learn/record_check_iap_expire.php"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];    
    
    [request setPostValue:device_uniqueIdentifier forKey:@"udid"];
    [request setPostValue:BundleIdentifier forKey:@"productid"];    
    
    [request setRequestMethod:@"POST"];
    
    [request setValidatesSecureCertificate:NO];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(record_check_iap_expire_Finish:)];
    [request setDidFailSelector:@selector(record_check_iap_expire_Fail:)];    
    [request startAsynchronous];
    
    
    
    
    
}

-(void)record_check_iap_expire_Finish:(ASIHTTPRequest *)request{
   
    NSString *response = [request responseString];
    NSLog(@"record_check_iap_expire:%@",response);    
   
    
    NSArray * Timestamp_array=[response componentsSeparatedByString:@":"];     
    
    if ([[Timestamp_array objectAtIndex:0] isEqualToString:@"ERROR"]  ) {
        //表示資料取出失敗
        NSLog(@"表示取出重要資料失敗");
        p_expire_Date=@"Server Error";   
        
        myTable.dataSource = self;	//連結資料 UITableViewDataSource
        myTable.delegate=self; //連結動作 UITableViewDelegate    
        //理論上 用datasource就會重新下載資料 是不用再次重載資料
        
        [myTable reloadData];
        
        [ActivityIndicator stopAnimating];	        
        
    }
    else{
        //資料取出成功
        
        //將字串的每個elements 分解出來      
        NSMutableDictionary *jsonvalue_elements = [response JSONValue];
        
        //取出所有的資料
                
        p_lastlogin_Date=[[jsonvalue_elements objectForKey:@"lastlogin_Date"] retain];
        p_firstentry_Date=[[jsonvalue_elements objectForKey:@"firstentry_Date"] retain];
        p_expire_Date_unix=[[jsonvalue_elements objectForKey:@"expire_datetime_unix"] retain];
        p_expire_status=[[jsonvalue_elements objectForKey:@"expire_status"] retain];  
        
        //
        //最後到期日
        NSDate* expireDate = [NSDate dateWithTimeIntervalSince1970:[ p_expire_Date_unix intValue]  ];        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MMM-dd HH:mm:ss";
        
        NSString *timeStamp = [dateFormatter stringFromDate:expireDate];
        NSLog(@"到期日=%@",timeStamp); 
        p_expire_Date=[timeStamp retain];        
        [dateFormatter release];      
        
        //顯示訊息
        UIAlertView *ia;
        ia=[[UIAlertView alloc] initWithTitle:@"Expire Date Info" message:[NSString stringWithFormat: @"Expire Date is:%@",p_expire_Date ] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [ia show];	
        [ia release];	          
       /*      
        //利用下面的城市可以列印出所有的值
        for (NSDictionary *s in jsonvalue_elements ) {
            NSLog(@"%@:%@",s,[jsonvalue_elements objectForKey:s]   );
        }            
       */
        myTable.dataSource = self;	//連結資料 UITableViewDataSource
        myTable.delegate=self; //連結動作 UITableViewDelegate    
        //理論上 用datasource就會重新下載資料 是不用再次重載資料
        
        [myTable reloadData];
        
        [ActivityIndicator stopAnimating];	        
        
        
    }
        
    
}
-(void)record_check_iap_expire_Fail:(ASIHTTPRequest *)request{
   NSLog(@"record_check_iap_expire_Fail"); 
    
   p_expire_Date=@"Server Error";    
    
    
    myTable.dataSource = self;	//連結資料 UITableViewDataSource
    myTable.delegate=self; //連結動作 UITableViewDelegate    
    //理論上 用datasource就會重新下載資料 是不用再次重載資料
    
    [myTable reloadData];
    
    [ActivityIndicator stopAnimating];	 
    
    
    
    
}



#pragma mark -
#pragma mark  網路商店資料下載結束
-(void)productsRequest_didReceiveResponse{
   
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        
    if ([[prefs objectForKey:@"iap_type" ] isEqualToString:@"Auto-Renewable Subscriptions"]) {
       //標記:自動續約 還要取出到期日是多久 並且判斷是否到期
        [self record_check_iap_expire];
    
    }
    else{
        //一次買斷
        
        //為何要將委託事件移到此處？主要是因為商品的資料要重網路上取得 如果一開始就執行datasource 就會出現資訊不完整的出現
        //所以就是等取出商品資料後 再委托事件
        myTable.dataSource = self;	//連結資料 UITableViewDataSource
        myTable.delegate=self; //連結動作 UITableViewDelegate    
        //理論上 用datasource就會重新下載資料 是不用再次重載資料
        
        [myTable reloadData];
        
        [ActivityIndicator stopAnimating];	        
        
    }
    
    
    
    
	
}


#pragma mark -
#pragma mark  退出至上一層
-(void)slideOut{
		
	
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        //[delegate_UIPopoverController dismissPopoverAnimated:YES]; 
       
        if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ){
            //垂直
            [self dismissModalViewControllerAnimated:YES];  
            
            [[(AppDelegate * )AppleDeglate Master_popController] presentPopoverFromBarButtonItem: 
             [(SplitViewDelegate *)[(AppDelegate * )AppleDeglate splitViewDelegate] showmasterUIBarButtonItem]  permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];              
            
            
        }
        else{
            //水平
            //[delegate_UIPopoverController dismissPopoverAnimated:YES]; 
             [self dismissModalViewControllerAnimated:YES];                         
        }
        
        
        
        
        
        
        
    }    
	else{
       [self.delegate  InAppPurchase_flipsideViewControllerDidFinish:self];    
    }
    
    
    
}

 @end
